//
//  Color.swift
//  SeeFM_Swift
//
//  Created by CBCT_MBP on 2021/5/24.
//

import Foundation

#if canImport(UIKit)
import UIKit

public extension UIColor {
    
    convenience init(hex: UInt32, alpha: CGFloat = 1.0) {
        
        let red = CGFloat((hex & 0xFF0000) >> 16) / 255.0
        let green = CGFloat((hex & 0x00FF00) >> 8) / 255.0
        let blue = CGFloat(hex & 0x0000FF) / 255.0
        
        self.init(red: red, green: green, blue: blue, alpha: alpha)
        
    }
    
    class func colorWith(hex: String?) -> UIColor? {
        guard let hexString = hex else { return nil }
        var trimedStr = hexString.trimed()
        trimedStr = trimedStr.replacingOccurrences(of: "0x", with: "")
        trimedStr = trimedStr.replacingOccurrences(of: "#", with: "")
        if let hexValue = UInt32(trimedStr, radix: 16) {
            return UIColor(hex: hexValue)
        }
        
        return nil
    }
    
    var imageValue: UIImage {
        let rect = CGRect.init(origin: .zero, size: CGSize.init(width: 1, height: 1))
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        context?.setFillColor(self.cgColor)
        context?.fill(rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage!
    }
    
}


#endif
